/* eslint-disable consistent-return */
import React, { Component } from 'react';
import { ExclamationCircleOutlined , UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { requestHeadersMd5 , uniqueArray } from '@/utils/utils';

import { Modal, Row, Col, Checkbox, Upload,Button,Tooltip, Select, Input, message } from 'antd';
import { connect } from 'dva';


const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
@connect(({ problempage: { proObjList, probTypeList, alrtObjsList, visible } }) => ({
  proObjList,
  probTypeList,
  alrtObjsList,
  visible,
}))
@Form.create()
class ProModal extends Component {
  state = {
    affixList: [],
    affixIds:[],
    uploadUrl: '/csApi/fileServer/uploadFile',
    downloadUrl: '/csApi/fileServer/downloadFile',
    confirmLoading: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { selectedRowKeys, busiType } = this.props;
    dispatch({
      type: 'problempage/addProbPopupView',
      payload: {
        busiIds: selectedRowKeys,
        busiType,
      },
    });
  }

    // 文件上传
    changeUpload = (info, listContFile) => {
      let { fileList } = info;
      const { file } = info;
      const { downloadUrl, affixIds} = this.state;
      // const { getFileInfo } = this.props;
      const newData = listContFile.map(item => ({ ...item }));
      if (file.status === 'done' && file.response.success) {
        const fileId = file.response.data.split('|')[0];
        const fileName = file.response.data.split('|')[1];
        fileList.map(files => {
          const temp = files;
          temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
          temp.linkProps = { download: `${fileName}` };
        });
        newData.push({
          uid: file.uid,
          affixId: fileId,
          affixName: fileName,
        });
        this.setState({ affixList: newData });
        // getFileInfo(newData);
        this.setState({ affixIds: newData });
        console.log(newData,'文件上传');
        message.success('文件上传成功！');
      } else {
        fileList = [];
        if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
          message.error('上传失败！');
        }
        return fileList;
      }
    };
  

    // 移除文件
    removeFile = (file, listContFile) => {
      const { affixIds} = this.state;
      // const { getFileInfo } = this.props;
      const newData = listContFile.filter(item => item.uid !== file.uid);
      // console.log(newData,'newData');
      this.setState({ affixList: newData });
      this.setState({ affixIds: newData });

      // getFileInfo(newData);
    };

    // 文件限制大小
    beforeUpload = () => {};

  // 弹框关闭
  handleCancle = () => {
    const { form, onCancel, dispatch } = this.props;
    // this.props.onCancel && this.props.onCancel();
    dispatch({
      type: 'problempage/updateModalData',
      payload: {
        visible: false,
      },
    });
    if (onCancel) {
      onCancel();
    }
    form.resetFields();
  };

  // 处理姓名的文字显示
  handleContent = paramList => {
    const tempArr = [];
    const tempArr2 = [];
    let nameContent = '';
    let nameTitle = '';
    // 处理重名
    const nameList = uniqueArray(paramList, 'empName');
    nameList.map(value => {
      tempArr.push(value.empName);
      tempArr2.push(value.empName);
      return true;
    });

    nameTitle = tempArr2.join('、');
    if (tempArr.length >= 3) {
      const str1 = tempArr.filter((item, index) => index <= 2).join('、');
      nameContent = `${str1}等多人`;
      // nameContent = `${str1}等${tempArr.length}人`;
    } else {
      nameContent = tempArr.join('、');
    }
    return (
      <Tooltip placement="top" title={<div>{nameTitle}</div>}>
        {nameContent}
      </Tooltip>
    );
  };
  //

  // getProType = () => {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: 'problempage/fetchProType',
  //     payload: {},
  //   });
  // };

  // 标记问题人员确定
  handleOk = () => {
    const { selectedRowKeys, busiType, dispatch, form, onOk = () => {}, proObjList } = this.props;
    const probFlag = proObjList.every(item => item.probFlag === 1);
    if (probFlag && proObjList.length) {
      message.warning('已标记问题人员，不可重复标记，请在问题人员列表查看并处理');
      return;
    }
    const {
      affixIds,
    } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      const obj = values;
      delete obj.affixIds;
      if (!err) {
        if (affixIds.length) {
          affixIds.map(f => {
            const ff = f;
            delete ff.uid;
          });
        }
        this.setState({ confirmLoading: true });
        dispatch({
          type: 'problempage/addProb',
          payload: {
            busiIds: selectedRowKeys,
            busiType,
            affixIds,
            ...values,
          },
        }).then(() => {
          this.setState({ confirmLoading: false });
          onOk();
        });
      }
    });
  };

  // handlePro = (proObjList, proStatus, proObjData) => {
  //   if (proStatus && proStatus.length) {
  //     if (proObjData && proObjData.length) {
  //       proObjData.forEach(data => {
  //         proStatus.forEach(status => {
  //           if (Number(data.value) === Number(status.ass)) {
  //             data.execState = status.execState;
  //             data.probFlag = status.probFlag;
  //           }
  //           if (data.value == 1) {
  //             if (status.ass != 2) {
  //               data.execState = status.execState;
  //               data.probFlag = status.probFlag;
  //             }
  //           }
  //         });
  //       });
  //     } else {
  //       proObjList.forEach(item => {
  //         const tempItem = item;
  //         proStatus.forEach(status => {
  //           if (Number(item.value) === Number(status.ass)) {
  //             tempItem.execState = status.execState;
  //             tempItem.probFlag = status.probFlag;
  //           }
  //         });
  //       });
  //     }
  //   }
  // };

  // 渲染问题对象
  renderStatus = proObjData => {
    if (proObjData && proObjData.length) {
      return (
        <Checkbox.Group style={{ width: '100%', verticalAlign: '-4px' }}>
          <Row>
            {proObjData && proObjData
              ? proObjData.map((item, i) => {
                  const index = i;
                  if (Number(item.subExecFlag) === 1) {
                    return (
                      <Col span={8} key={index}>
                        <Checkbox value={item.itemCode} disabled checked>
                          {item.itemName}
                        </Checkbox>
                      </Col>
                    );
                  }
                  if (Number(item.probFlag) === 1) {
                    return (
                      <Col span={8} key={index}>
                        <ExclamationCircleOutlined
                          style={{ fontSize: 16, color: '#f00', marginRight: 5 }}
                        />
                        {item.itemName}
                      </Col>
                    );
                  }
                  return (
                    <Col span={8} key={index}>
                      <Checkbox value={item.itemCode}>{item.itemName}</Checkbox>
                    </Col>
                  );
                })
              : null}
          </Row>
        </Checkbox.Group>
      );
    }
    return (
      <Checkbox.Group style={{ width: '100%', verticalAlign: '-4px' }}>
        <Row>
          {proObjData && proObjData
            ? proObjData.map((item, i) => {
                const index = i;
                if (Number(item.execState) === 1) {
                  return (
                    <Col span={8} key={index}>
                      <Checkbox value={item.value} disabled checked>
                        {item.label}
                      </Checkbox>
                    </Col>
                  );
                }
                if (Number(item.probFlag) === 1) {
                  return (
                    <Col span={8} key={index}>
                      <ExclamationCircleOutlined
                        style={{ fontSize: 16, color: '#f00', marginRight: 5 }}
                      />
                      {item.label}
                    </Col>
                  );
                }
                return (
                  <Col span={8} key={index}>
                    <Checkbox value={item.value}>{item.label}</Checkbox>
                  </Col>
                );
              })
            : null}
        </Row>
      </Checkbox.Group>
    );
  };

  // 问题人员类型更改
  probTypeChange = val => {
    const { form, probTypeList } = this.props;
    const result = probTypeList.filter(item => item.probTypeId === val)[0];

    form.setFieldsValue({
      probTypeDesc: result && result.probTypeName,
    });
  };

  render() {
    const formItemLayout = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 18 } },
    };
    const { uploadUrl, affixList } = this.state;

    const uploadProps = {
      beforeUpload: info => this.beforeUpload(info, affixList),
      action: uploadUrl,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, affixList),
      onRemove: file => this.removeFile(file, affixList),
    };
    const {
      form: { getFieldDecorator },
      visible,
    } = this.props;
    const {
      selectedRows,
      proObjList,
      isAlertObj,
      isProObj,
      probTypeList,
      // proObjData,
      isProType,
      alrtObjsList,
    } = this.props;
    const { confirmLoading } = this.state;
    // console.log(proObjList, 'proObjList') // 问题对象数组
    // console.log(probTypeList, 'probTypeList') // 问题人员类型数组
    // console.log(proStatus, 'proStatus') // 问题对象中每一个的状态
    // console.log(proObjData, 'proObjData') // 问题对象数组
    // if (proStatus && proStatus.length) {
    //   this.handlePro(proObjList, proStatus, proObjData);
    // }
    // if (!sendLoading) {

    return (
      <Modal
        title="标记问题人员"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancle}
        destroyOnClose
        confirmLoading={confirmLoading}
      >
        <div>
          {selectedRows.length > 1?(<div style={{ marginBottom: 20 ,color:'#ff4d4f'}}>单个人员可上传附件内容</div>):null}
          <Row>
            <Col>
              <FormItem {...formItemLayout} label="姓名">
                <Col>{this.handleContent(selectedRows)}</Col>
              </FormItem>
            </Col>
          </Row>
          {isAlertObj ? (
            <Row>
              <Col>
                <FormItem {...formItemLayout} label="提醒对象">
                  {getFieldDecorator('alrtObjs', {
                    rules: [{ required: true, message: '请选择提醒对象' }],
                  })(
                    <Checkbox.Group style={{ width: '100%' }}>
                      <Row>
                        {alrtObjsList &&
                          alrtObjsList.map(item => (
                            <Col span={8} key={item.itemCode}>
                              <Checkbox value={item.itemCode}>{item.itemName}</Checkbox>
                            </Col>
                          ))}
                      </Row>
                    </Checkbox.Group>
                  )}
                </FormItem>
              </Col>
            </Row>
          ) : null}
          {isProObj ? (
            <Row>
              <Col>
                <FormItem {...formItemLayout} label="问题对象">
                  {getFieldDecorator('probObjs', {
                    rules: [{ required: true, message: '请选择问题对象' }],
                  })(this.renderStatus(proObjList))}
                </FormItem>
              </Col>
            </Row>
          ) : null}
          <Row>
            {isProType ? (
              <Col>
                <FormItem {...formItemLayout} label="问题人员类型">
                  {getFieldDecorator('probTypeId', {
                    rules: [{ required: true, message: '请选择问题人员类型' }],
                  })(
                    <Select
                      style={{ width: '100%' }}
                      showSearch
                      allowClear
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      optionFilterProp="children"
                      onChange={this.probTypeChange}
                      placeholder="请选择"
                    >
                      {probTypeList &&
                        probTypeList.map(value => (
                          <Option key={value.probTypeId}>{value.probTypeName}</Option>
                        ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            ) : null}
          </Row>
          <Row>
            <Col>
              <FormItem {...formItemLayout} label="问题说明">
                {getFieldDecorator('probTypeDesc', {
                  rules: [{ required: true, message: '请填写问题说明' }],
                })(
                  <TextArea
                    placeholder="请输入问题说明"
                    autosize={{ minRows: 3, maxRows: 6 }}
                    maxLength={1000}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          {selectedRows.length === 1?(
            <Row>
              <Col>
                <Form.Item {...formItemLayout} label="附件">
                  {getFieldDecorator('affixIds', {
                  rules: [{ required: false, message: '请输入' }],
                })(
                  <Upload {...uploadProps} beforeUpload={this.beforeUpload}>
                    {affixList.length < 5 ? (
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    ) : null}
                  </Upload>
                )}
                </Form.Item>
              </Col>
            </Row>
          ):null}

        </div>
      </Modal>
    );
  }
}

export default ProModal;
